function pageInit(){
	getData(getDataUrl, requestParam);
	resData             = resData.data;
	$('#id_lott_shangqi').html(resData.shangqi.period);
	$('#id_lott_lotting').html(resData.lotting.period);
	$('#id_lott_next').val(resData.nextbet.period);
	var now_timestamp   = (Date.parse(new Date()) / 1000) * 1; // js的时间戳会带毫秒
	// 当前期号结束时间减掉当前时间戳为剩下时间
//	running_time = resData.lotting.stoptime - now_timestamp;
	running_time = resData.lotting.stoptime - resData.suportData.nowTime;
	daojishi();
	// 上期开奖
	clearTimeout(clear_kj_ready);
	shangqi_kj_reday(2000);
}

/**
 * =========================================================================
 * 倒计时计算，返回00:00:00形式倒计时
 * @param second
 */
function daojishi (){
	var hour   = '00';
	var minute = '00';
	var second = '00';
	if (running_time <= 0){
		$('.tag_runningtime').html(hour + ':' + minute + ':' + second);
		// 当前期号结束，获取下批期号信息， 并重新载入数据.
		var content_msg  = resData.shangqi.period + '期已截止<br/>';
			content_msg += '当前期号<font style="color: red;">' + $('#id_lott_next').val() + '</font><br/>';
			content_msg += '投注时请注意期号';
			showMsg('温馨提示', content_msg, '');
			setTimeout("pageInit()", 1000);
		return;
	}
	hour       = parseInt(running_time / (60 * 60));
	minute     = parseInt(running_time / (60));
	second     = parseInt(running_time % (60));
	if(hour == 0){
		hour = '00';
	}else if(hour > 0 && hour < 10){
		hour = '0' + hour;
	}
	if(minute == 0){
		minute = '00';
	}else if(minute > 0 && minute < 10){
		minute = '0' + minute;
	}
	if(second == 0){
		second = '00';
	}else if (second > 0 && second < 10){
		second = '0' + second;
	}
	$('#tag_runningtime').html(hour + ':' + minute + ':' + second);
	running_time--;
	setTimeout("daojishi()", 1000);
}


/**
 * 获取页面数据
 * url：请求路劲
 * param：提交参数
 * reload：是否刷新页面
 */
function getData(url, param={}, reload=''){
	$.ajax({  
		type:'post',    
	    url: url,  
	    data:'data=' + JSON.stringify(param),  
	    cache:false,  
	    dataType:'json',  
	    async:false,
	    success:function(res){  
	    	if(res.msg){
	    		if(res.status == 'success'){
	    			showMsg('温馨提示', res.msg, reload);		    		
		    	}else{
		    		var msg = '网络错误，请刷新页面重试';
		    		if(res.msg){
		    			msg = res.msg;
		    		}
		    		showMsg('温馨提示', msg);
		    	}
	    	}else{
	    		resData = res;
	    	}
	    }  
	})
}

/**
 * 上期开奖前面旋转2秒后展示开奖结果
 * @param seconds
 */
var shangqi_kj = 1;
var clear_kj_ready   = '';
function shangqi_kj_reday(seconds){
	if(seconds <= 0){
		shangqi_kaijiang(resData.shangqi.code);
		return;
	}
	if(!$.isEmptyObject(resData.shangqi.code)){
		// 如果上期有开奖，则准备展示上期开奖结果
		seconds = seconds - 50;
	}
	if(shangqi_kj > 11) shangqi_kj = 1;
	$('#id_shangqi_open em').html(shangqi_kj);
	shangqi_kj++;
	clear_kj_ready = setTimeout('shangqi_kj_reday(' + seconds + ', "' + resData.shangqi.code + '")', 50);
}

/**
 * 上期开奖结果，这里主要是js效果以及控制
 */
function shangqi_kaijiang(code_str){
	var kaijiang_code = code_str.split(',');
	for(var i = 0; i < 5; i++){ $('#id_shangqi_open em').eq(i).html(kaijiang_code[i]); }
}

/**
 * 选择主玩法填充从玩法
 * @returns
 */
var type_code   = '';
var follow_code = '';
function fillFollowPlay (obj=''){
	$('#id_current_mainplay').html($('#id_main_play li[class="curr"]').html());
	$('#id_follow_playlist').html('');
	
	// 置空从玩法
	play_follow = {'follow_index':'', 'base':''};
	var str     = '';
	$.each(play_main.base.playType, function (i, v){
		// 如果请求来源于切换玩法，则重新设定从玩法内容
		if(i == $(obj).attr('amv')){
			play_follow.follow_index = i;
			play_follow.base         = play_main.play[i];
		}
		str  = '<li class="fix otherPosition">';
		str += '	<span>' + v.title + '</span>';
		str += '	<div class="fix">';
		$.each(v.followPlay, function (i1, v1){
			if($.isEmptyObject(play_follow.base)){
				play_follow.follow_index = i + '|' + i1;
				type_code                = i;
				follow_code              = i1;
				play_follow.base         = v1;
				play_group               = i;
			}
			str += '	<a class="tag_followplay_item" amv="' + i + '|' + i1 + '">' + v1.title + '</a>';
		});
		str += '	</div>';
		str += '</li>';
		$('#id_follow_playlist').append(str);
	})
	$('#id_follow_playlist a').eq(0).addClass('curr');
	user_play   = play_main.main_index + '-' + play_follow.follow_index;
	$('#id_now_play_title').html(play_main.base.title + ' ' + play_follow.base.title);
	ready_bet             = {};
	betting[user_play]     = {
		'1'   : [],
		'2'   : [],
		'3'   : [],
		'4'   : [],
		'5'   : [],
	};
}

/**
 * 更新玩法操作界面
 * @returns
 */
function fillPlayBody(){
	var nowPlay = resData.codeKeyList[play_main.main_index + '-'][type_code + '|'][follow_code];
	if(!$.isEmptyObject(nowPlay)){
		$('#id_play_tips').html(nowPlay.explain);
		// 动态读取该用户在当前彩种玩法中的实际赔率信息
		$('.tag_pc_bonus').html(nowPlay.odds);
	}else{
		// 选择从玩法，加载从玩法方式内容与说明
		$('.tag_play_explain').html('多重玩法');
	}
	// 填充玩法区域内容
	$('#id_play_body').html('');
	var content  = '';
	// 选项标识的唯一ID
	var item_id  = '';
	// 玩法内容
	var playData = '';
	
	if(play_follow.base.item.option == 'import'){
		content += '<div class="textareaNumber">';
		content += '	<textarea class="tag_import_content" placeholder=" 每一注号码之间请使用空格分开，每注之间以回车、逗号或分号进行分隔"></textarea>';
		content += '</div>';
	}else{
		$.each(play_follow.base.item, function (index, value){
			content += '<div class="selectNumber fix">';
			content += '	<div class="title fix">';
			content += '		<em><p>' + value.name + '</p></em> ';
			content += '	</div>';
			content += '	<div class="numberContent">';
			item_id  = '';
			playData = resData.playItem.baseItem[value.option];
			if(playData.min){
				for(var i = playData.min; i <= playData.max; i++){
					content += '	<a class="tag_choice_item" group="' + index + '" ami="' + i + '" ><span>' + i + '</span></a>';
				}
			}else{
				$.each(playData.routine, function (i, v){
					content += '	<a class="tag_choice_item" group="' + index + '" ami="' + v + '" ><span>' + v + '</span></a>';
				})
			}
			content += '	</div>';
			content += '</div>';
		});
	}
	if($.inArray(play_main.main_index + '-' + play_follow.follow_index, ['QWX-DDS']) > -1){
		// 给主div增加 quWei 标识
		$('#id_sscMain').addClass('quWei');
	}else{
		$('#id_sscMain').removeClass('quWei');
	}
	$('#id_play_body').html(content);
	ready_bet             = {};
	betting[user_play]     = {
		'1'   : [],
		'2'   : [],
		'3'   : [],
		'4'   : [],
		'5'   : [],
	};
}

/**
 * 根据预投注内容计算有效投注数
 */
var valid_betnum = 0;
var js_bet_item  = { '1' : [], '2' : [], '3' : [], '4' : [], '5' : [] };
function bet_jisuan(){
	console.log(user_play);
	// 有效的投注数
	var valid_betnum = 0;
	if($.isEmptyObject(ready_bet) || $.isEmptyObject(ready_bet.bet_item)){
		$('.tag_bet_count').html(valid_betnum);
		return;
	}
	var multiple     = $('#id_user_bet_beishu').val();
	
	$.each(ready_bet.bet_item, function (i, v){
		if(v.check == 'success'){
			if(v.nums){
				// 如果有单独设置注数，则单独累加
				valid_betnum += v.nums;
			}else{
				valid_betnum++;
			}
		}
		// 倍数
		ready_bet.bet_item[i].multiple = multiple;
		// 金额
		ready_bet.bet_item[i].eo_money = default_bet_money;
	})
	
	$('.tag_bet_count').html(valid_betnum);
	// 获取金额单位
	var money_unit_dom = $('.tag_money_unit[class="tag_money_unit curr"]');
	var money_unit     = money_unit_dom.attr('amv');
	var money_unit_cn  = money_unit_dom.attr('amt');
	var amount         = 0; 
	// 开始计算金额:  默认每注金额 * 金额单位 * 投注组数 * 投注倍数
	amount = parseFloat(default_bet_money * money_unit * multiple * valid_betnum).toFixed(2);
	
	ready_bet.lott_id        = resData.lotteryInfo.id;
	ready_bet.bet_money_unit = money_unit;
	ready_bet.bet_zhushu     = valid_betnum;
	ready_bet.multiple       = multiple;
	ready_bet.bet_amount     = parseFloat(amount).toFixed(2);
	ready_bet.maxwinner      = (1 * oddsArr[0] * parseFloat(money_unit)).toFixed(2);
	ready_bet.betting        = betting[user_play];
	ready_bet.period         = resData.lotting.id;
	$('#id_choice_zhushu').html(valid_betnum);
	$('#id_choice_amount').html(amount);
}

//如果用户选择号码产生一注以上有效号码，则展示投注底部投注信息说明，并点亮购物车选项
function checkBetsNums(){
	var all_bets_nums = ready_bet.bet_zhushu;
	// 没有有效的投注
	if(all_bets_nums <= 0) return;
	$('#id_sscFooter').removeClass('active');
	if(all_bets_nums <= 0) return;
	// 展示用户投注设置选项（倍数与金额单位）
	$('#id_user_bets_set').show();
	$('#id_sscFooter').addClass('active');
	// 展示用户所选择的投注项
	var bettingData = ready_bet.betting;
	var betting_str = '';
	if(!$.isEmptyObject(bettingData[1])){
		betting_str += bettingData[1].join(' ') + ', ';
	}
	if(!$.isEmptyObject(bettingData[2])){
		betting_str += bettingData[2].join(' ') + ', ';
	}
	if(!$.isEmptyObject(bettingData[3])){
		betting_str += bettingData[3].join(' ') + ', ';
	}
	if(!$.isEmptyObject(bettingData[4])){
		betting_str += bettingData[4].join(' ') + ', ';
	}
	if(!$.isEmptyObject(bettingData[5])){
		betting_str += bettingData[5].join(' ');
	}
	$('#id_betting_str').html(betting_str);
}


/**
 * 用户选择的投注项增加到购物车中
 */
function addCart(){
	if(ready_bet.bet_zhushu <= 0) return;
	// 清除选项中无用的投注数据（用户手动输入的时候，如果输入了奇葩选项）
	var checkBet = ready_bet.bet_item;
	var tmp      = [];
	$.each(checkBet, function (i, v){
		if(v.check == 'success'){
			// 移除无用数据(直接循环删除， 会有问题，移除之后数据源的下标立刻就变了)
			tmp.push(v);
		}
	});
	ready_bet.bet_item = tmp;
	// 记录当前加入购物车的序号，用作对应删除购物车
	cart_index++;
	// 计算用户投注的内容，以后不用重复计算
	var bettingData       = ready_bet.betting;
	var bet_string        = '';
	if(!$.isEmptyObject(bettingData[1])){
		bet_string += bettingData[1].join(' ') + ', ';
	}
	if(!$.isEmptyObject(bettingData[2])){
		bet_string += bettingData[2].join(' ') + ', ';
	}
	if(!$.isEmptyObject(bettingData[3])){
		bet_string += bettingData[3].join(' ') + ', ';
	}
	if(!$.isEmptyObject(bettingData[4])){
		bet_string += bettingData[4].join(' ') + ', ';
	}
	if(!$.isEmptyObject(bettingData[5])){
		bet_string += bettingData[5].join(' ');
	}
	ready_bet.bet_string  = bet_string;
	ready_bet.cart_index  = cart_index;
	// 基础投注金额
	ready_bet.eo_money    = default_bet_money;
	betCart.push(ready_bet);
	var play_str  = '';
	var play_type = '';
	// 将添加到购物车的数据，追加到购物车列表
	$('#id_cart_betting_list').html(function (){
		var str = '<li amv="' + cart_index + '">';
		str    += '		<em>' + bet_string + '</em> ';
		str    += '		<span>前三直选复式 ' + ready_bet.bet_zhushu + '注×' + (default_bet_money * ready_bet.bet_money_unit) + '元×' + ready_bet.multiple + '倍  = ' + ready_bet.bet_amount + '元</span>';
		str    += '		<a class="tag_drop_bet" amv="' + cart_index + '"></a>';
		str    += '</li>';
		$(this).append(str);
	});
	balanceCart();
	// 初始化投注预览
	reBetInit();
	// 重构购物车
	balanceCart();
}
/**
 * 重选玩法，初始化投注预览
 */
function reBetInit(){
	ready_bet             = {};
	betting[user_play]    = {
		'one'   : new Array(),
		'two'   : new Array(),
		'three' : new Array(),
	};
	// 初始化页面选择项
	fillPlayBody();
	reBetView();
}

/**
 * 初始化投注预览
 */
function reBetView(){
	// 初始化底部投注预览信息
	$('#id_sscFooter').removeClass('active');
	$('#id_choice_zhushu').html('0');
	$('#id_choice_amount').html('0.00');
	$('#id_betting_str').html('');
	$('#id_user_bet_beishu').val('1');
	$('.tag_money_unit').removeClass('curr');
	$('.tag_money_unit:eq(0)').addClass('curr');
	$('#id_user_bets_set').hide();
	$('#id_cart_nums').html(betCart.length);
	$('#id_cart_nums').show();
}

/**
 * 删除购物车
 */
function dropCart(index){
	var drop_id = 0;
	$.each(betCart, function (i, v){
		drop_id = i;
		// 获取到当前购物车中要删除选项的下标
		if(v.cart_index == index) return false;
	})
	// 删除投注项
	betCart.splice(drop_id, 1);
	balanceCart();
	$('#id_cart_nums').html(betCart.length);
	if(betCart.length == 0){
		$('#id_cart_nums').hide();
	}
	// 重构购物车
	balanceCart();
}

/**
 * 清空购物车
 */
function clearCart(){
	$('#id_cart_betting_list').html('');
	betCart = [];
	// 重新结算数据
	balanceCart();
	// 页面样式初始化
	$('#id_cart_zhus').html('0');
	$('#id_cart_amounts').html('0.00');
	$('#id_cart_nums').html('0');
	$('#id_cart_nums').hide();
}

///**
// * 结算购物车数据预览
// */
//function balanceCart(){
//	var zhus    = 0;
//	var amounts = 0;
//	$.each(betCart, function (i, v){
//		amounts += parseFloat(v.bet_amount);
//		zhus    += v.bet_zhushu;
//	})
//	$('#id_cart_zhus').html(zhus);
//	$('#id_cart_amounts').html(amounts.toFixed(2));
//}

/**
 * 重构购物车
 */
function reBuildCart(){
	$('#id_cart_betting_list').html(function (){
		$(this).html('');
		var str          = '';
		var play_str     = '';
		var play_type    = '';
		var play_type_st = '';
		$.each(betCart, function (i, v){
			play_type    = v.bet_name.split('-');
			play_type_st = play_type[1].split('|');
			play_str     = resData.playItem.mainPlay[play_type[0]].title + ' ' + resData.playItem.mainPlay[play_type[0]].playType[play_type_st[0]].title + ' ' + resData.playItem.mainPlay[play_type[0]].playType[play_type_st[0]].followPlay[play_type_st[1]].title;
			cart_index   = i;
			str     = '<li amv="' + v.cart_index + '">';
			str    += '		<em>' + v.bet_string + '</em> ';
			str    += '		<span>' + play_str + v.bet_zhushu + '注×' + (default_bet_money * v.bet_money_unit) + '元×' + v.multiple + '倍  = ' + v.bet_amount + '元</span>';
			str    += '		<a class="tag_drop_bet" amv="' + v.cart_index + '"></a>';
			str    += '</li>';
			$('#id_cart_betting_list').append(str);
		});
	});
}

/**
 * 结算购物车
 */
function balanceCart(){
	// 空购物车
	if($.isEmptyObject(betCart)) return;
	// 检查是否有追号
	var is_chase = $('#id_chase').prop('checked');
	var chase_beishu = $('#id_chase_beishu').val();
	var chase_qishu  = $('#id_chase_qishu').val();
	var tmp_sum      = 0;
	// 统计数据
	var zhus     = 0;
	var amounts  = 0;
	$.each(betCart, function (i,v){
		if(is_chase == true){
			// 追号， 将所有投注信息变更为基础1倍。（因为追号会重设投注倍数）
			betCart[i].multiple = 1;
		}
		tmp_sum               = parseFloat(v.bet_zhushu * v.eo_money * v.bet_money_unit * betCart[i].multiple);
		betCart[i].bet_amount = parseFloat(tmp_sum * chase_beishu * chase_qishu).toFixed(2);
		amounts += tmp_sum * chase_beishu * chase_qishu;
		zhus    += parseInt(v.bet_zhushu);
	});
	// 重构购物车
	reBuildCart();
	$('#id_cart_zhus').html(zhus);
	$('#id_cart_amounts').html(amounts.toFixed(2));
}

//安全提交
var securityPost       = true;
/**
 * 投注
 */
function doBet(){
	if(securityPost == false){
		showMsg('温馨提示', '请等待提交结果');
		return;
	}
	// 锁定提交
	securityPost = false;
	if(betCart.length <= 0) {
		showMsg('温馨提示', '请选择有效的投注号');
		return;
	}
	var param    = {'lott_id':resData.lotteryInfo.id, 'cart':betCart};
	// 检查是否有追号设置
	if($('#id_chase').prop('checked') == true){
		// 设置追号的倍数与期数
		param.multiple = $('#id_chase_beishu').val();
		param.qishu    = $('#id_chase_qishu').val();
		param.chase    = true;
	}
	// 安全提交限制
	securityPost = false;
	$.ajax({  
		type:'post',    
	    url: doBetUrl,  
	    data:'data=' + JSON.stringify(param),  
	    cache:false,  
	    dataType:'json',
	    success:function(res){  
	    	if(res.status == 'success'){
	    		showMsg('温馨提示', '<span style="color:red">投注成功</span>，您可以在我的账户查看注单详情', 'success');
	    		clearCart();
	    		// 初始化投注预览
	    		reBetInit();
			}else{
				showMsg('温馨提示', '投注失败，请重试', '');
			}
	    	// 释放提交
	    	securityPost = true;
	    },
	    error:function (XMLHttpRequest, textStatus, errorThrown){
	    	// 释放提交
	    	securityPost = true;
	    }
	})
}

/**
 * 投注预览
 */
function betViewMsg(){
	if($.isEmptyObject(betCart)) {
		showMsg('', '未选择投注内容');
		return;
	}
	var tmp_mp = '';
	var tmp_fp = '';
	var str    = resData.lotteryInfo.title + '：' + resData.lotting.period + '期<br/>';
	str    += '投注金额：' + $('#id_cart_amounts').html();
	str    += '投注内容：<br/>';
	$.each(betCart, function (i, v){
		tmp_mp = v.bet_name.split('-');
		tmp_fp = tmp_mp[1].split('|');
		str += '[' + resData.playItem.mainPlay[tmp_mp[0]].title + ',' + 
				resData.playItem.mainPlay[tmp_mp[0]].playType[tmp_fp[0]].title + ',' + 
				resData.playItem.mainPlay[tmp_mp[0]].playType[tmp_fp[0]].followPlay[tmp_fp[1]].title + '] ' + 
				v.bet_string + '<br/>';
	})
	showMsg('投注确认', str, 'bet');
}


//倒计时结束提示弹框
function showMsg(title='温馨提示', msg, type){
	if(!title){return}
	switch(type){
		case 'bet':
			var bet_status = false;
			layer.open({
				title: title,
				content: msg,
				className: 'layui-m-tag-msg',
				btn: ['投注','取消'],
				yes: function (index){
					doBet();
		        	layer.close(index);
				}
			});
			break;
		case 'success':
			layer.open({
	            title: '温馨提示',
	            content: '<span style="color:red">投注成功</span>，您可以在我的账户查看注单详情',
	            className: 'layui-m-tag-msg',
	            btn: ['继续投注', '查看注单'],
	            yes: function (index){
					// 继续投注
	            	layer.close(index);
	            },
	            no: function (index){
	            	// 查看注单
	            	window.location = memberBet;
	            }
	        });
			break;
		default:
			layer.open({
				title: title,
				content: msg,
				className: 'layui-m-tag-msg',
				btn: ['确定'],
				yes: function (index){
					layer.close(index);
				}
			});
			break;
	}
}




